package com.netsdk.web.callback;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.netsdk.common.Res;
import com.netsdk.config.AqieConfig;
import com.netsdk.config.websocket.WebSocketServer;
import com.netsdk.dto.EnterDTO;
import com.netsdk.lib.NetSDKLib;
import com.netsdk.lib.ToolKits;
import com.netsdk.utils.SpringUtils;
import com.sun.jna.Pointer;
import lombok.extern.slf4j.Slf4j;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

import static com.netsdk.common.Constant.UPLOAD;

/**
 * @Author aqie
 * @Date 2022/3/25 17:02
 * @desc
 */
@Slf4j
public class AnalyzerCallback implements NetSDKLib.fAnalyzerDataCallBack {

    private AnalyzerCallback() {
    }

    private static class CallBackHolder {
        private static final AnalyzerCallback cb = new AnalyzerCallback();
    }

    public static AnalyzerCallback getInstance() {
        return CallBackHolder.cb;
    }


    private BufferedImage gateBufferedImage = null;

    public int invoke(NetSDKLib.LLong lAnalyzerHandle, int dwAlarmType,
                      Pointer pAlarmInfo, Pointer pBuffer, int dwBufSize,
                      Pointer dwUser, int nSequence, Pointer reserved)
    {
        if (lAnalyzerHandle.longValue() == 0 || pAlarmInfo == null) {
            return -1;
        }
        AqieConfig aqieConfig = SpringUtils.getBean(AqieConfig.class);
        File path = new File(aqieConfig.getUpload());
        if (!path.exists()) {
            path.mkdir();
        }

        ///< 门禁事件
        if(dwAlarmType == NetSDKLib.EVENT_IVS_ACCESS_CTL) {
            NetSDKLib.DEV_EVENT_ACCESS_CTL_INFO msg = new NetSDKLib.DEV_EVENT_ACCESS_CTL_INFO();
            ToolKits.GetPointerData(pAlarmInfo, msg);

            // 保存图片，获取图片缓存
            String fileName = System.currentTimeMillis() + "GateSnapPicture.jpg";
            String snapPicPath = path + File.separator + fileName;  // 保存图片地址

            byte[] buffer = pBuffer.getByteArray(0, dwBufSize);
            ByteArrayInputStream byteArrInputGlobal = new ByteArrayInputStream(buffer);

            try {
                gateBufferedImage = ImageIO.read(byteArrInputGlobal);
                if(gateBufferedImage != null) {
                    ImageIO.write(gateBufferedImage, "jpg", new File(snapPicPath));
                }
            } catch (IOException e2) {
                e2.printStackTrace();
            }

            // log.info("图片以及门禁信息界面显示 {}", msg);

            try {
                String cardName = new String(msg.szCardName, "GBK").trim();
                msg.UTC.setTime(msg.UTC.dwYear, msg.UTC.dwMonth, msg.UTC.dwDay, msg.UTC.dwHour+8, msg.UTC.dwMinute, msg.UTC.dwSecond);
                String time = msg.UTC.toStringTime();
                DateTime dateTime = DateUtil.parse(time);
                long timeStamp = dateTime.getTime();
                int bStatus = msg.bStatus; // 正常
                String openMethods = Res.string().getOpenMethods(msg.emOpenMethod);
                String cardNo = new String(msg.szCardNo).trim();
                String userId = new String(msg.szUserID).trim(); // code
                String maskStatus = Res.string().getMaskStatus(msg.emMask);
                String temperature = msg.stuManTemperatureInfo.fCurrentTemperature+"";
                log.info(" {} 开门状态:{} 时间:{} 开门方式:{} 姓名名:{} code:{} 口罩:{} 温度:{}", fileName, bStatus, timeStamp, openMethods, cardName, userId, maskStatus, temperature);
                EnterDTO enterDTO = new EnterDTO().setUsername(cardName).setCode(userId).setTemperature(temperature)
                        .setFileName(UPLOAD + fileName)
                        .setTimeStamp(timeStamp).setBStatus(bStatus).setOpenMethods(openMethods).setMaskStatus(maskStatus);
                WebSocketServer socketServer = SpringUtils.getBean(WebSocketServer.class);
                socketServer.broadCastInfo(enterDTO);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return 0;
    }
}
